import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/pages/classify/entity/classify_data_entity.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

///分类页控制器
class ClassifyController extends BaseController with SingleGetTickerProviderMixin {
  // 分类列表
  List<ClassifyDataEntity> classifyLit = [];
  // 默认激活的索引
  int activeIndex = 0;
  // tab 控制器
  late TabController tabCtr;

  final pageController = PageController();

  // 二级分类广告
  ClassifyDataApiClassAdvGetListVO? adInfo;
  // 一级分类 id
  String firstId = '';

  // 二级分类列表
  late List<ClassifyDataChildren> secondList = [];
  // 品牌列表
  late List? brandList = [];

  @override
  void onInit() {
    super.onInit();

    getClassifyList();
    tabCtr = TabController(length: 2, vsync: this);
    // 监听 TabController 切换事件
    tabCtr.addListener(() {
      if (!tabCtr.indexIsChanging) {
        // 根据当前 Tab 索引调用相应的接口
        if (tabCtr.index == 1) {
          getBrandList();
        } else {
          getClassifyList();
        }
        pageController.jumpToPage(tabCtr.index);
      }
    });

    UmengCommonSdk.onPageStart('分类页');
  }

  // 获取分类列表
  void getClassifyList() async {
    Tools.showLoading();
    await Network.getGoodsClassify().then((value) {
      Tools.hideLoading();
      classifyLit = value
          .asMap()
          .entries
          .map((entry) {
            final index = entry.key; // 获取元素的下标
            final item = entry.value; // 获取元素的值
            try {
              var model = ClassifyDataEntity.fromJson(item);
              model.isSelected = index == activeIndex; // 判断是否被选中
              return model; // 返回模型
            } catch (e) {
              // 处理异常
              print('Error parsing item: $item, error: $e');
              return null; // 返回 null 以表示解析失败
            }
          })
          .where((element) => element != null) // 过滤掉 null 值
          .cast<ClassifyDataEntity>() // 确保类型为 ClassifyDataEntity
          .toList(); // 转换为列表
      getSecondClassify();
    }).catchError((onError) {
      Tools.hideLoading();
    });
    update();
  }

  // 获取品牌列表
  void getBrandList() {
    Tools.showLoading();
    Network.getBrandList().then((value) {
      Tools.hideLoading();
      brandList = value;
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  // 切换分类
  void changeClassify(int selectIndex) async {
    updateSelectedClassifyItem(selectIndex);
    activeIndex = selectIndex;
    secondList = [];
    await Future.delayed(const Duration(milliseconds: 100));
    getSecondClassify();
    update();
  }

  // 获取二级分类信息
  void getSecondClassify() {
    var fistLevelInfo = classifyLit[activeIndex];
    firstId = fistLevelInfo.id.toString();
    adInfo = fistLevelInfo.apiClassAdvGetListVO;
    secondList = fistLevelInfo.children ?? [];
    update();
  }

  void updateSelectedClassifyItem(int selectedIndex) {
    classifyLit.asMap().forEach((index, item) {
      item.isSelected = index == selectedIndex; // 仅在指定索引匹配时选中
    });
  }

  @override
  void onClose() {
    tabCtr.dispose();
    pageController.dispose();
    super.onClose();
    UmengCommonSdk.onPageEnd('分类');
  }

  @override
  void onPageRefresh() {
    super.onPageRefresh();
    // tabCtr.index = 0;
    activeIndex = 0;
    getClassifyList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }
}
